/**
 * Project Name:CourtTest元数据管理系统
 * File Name:SearchCourt.java
 * Package Name:main.java.com.search
 * Description:    TODO(用一句话描述该文件做什么)
 * Date:2016年6月15日下午4:44:11
 * Copyright (c) 2016, 中国软件与技术服务股份有限公司 版权所有.
 *
 */
package com.css.sword.knowing.search.test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;

import com.css.sword.knowing.search.HighLightField;
import com.css.sword.knowing.search.OrderField;
import com.css.sword.knowing.search.SearchField;
import com.css.sword.knowing.search.SearchInput;
import com.css.sword.knowing.search.SearchResult;
import com.css.sword.knowing.search.Searcher;
import com.css.sword.knowing.search.ValueRange;
import com.css.sword.knowing.search.aggregation.AggBucket;
import com.css.sword.knowing.search.aggregation.AggInput;
import com.css.sword.knowing.search.aggregation.AggResult;
import com.css.sword.knowing.search.aggregation.BucketResult;
import com.css.sword.knowing.search.aggregation.MetricsResult;
import com.css.sword.knowing.search.aggregation.SearchAndAggResult;
import com.css.sword.knowing.search.comm.SearchConst;
import com.css.sword.knowing.search.exception.ArgException;

/**
 * ClassName: SearchCourt <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * date: 2016年6月15日 下午4:44:11 <br/>
 *
 * @author hxCai
 * @version
 * @since JDK 1.7
 */
public class Group {

    private String indexName = "";
    private String[] typeName = {};

    private String[] keywords = {};

    private int pagesize = 10;
    private int pageno = 1;

    public String getIndexName() {
        return indexName;
    }

    public void setIndexName(String indexName) {
        this.indexName = indexName;
    }

    public String[] getTypeName() {
        return typeName;
    }

    public void setTypeName(String[] typeName) {
        this.typeName = typeName;
    }

    public String[] getKeywords() {
        return keywords;
    }

    public void setKeywords(String[] keywords) {
        this.keywords = keywords;
    }

    public int getPagesize() {
        return pagesize;
    }

    public void setPagesize(int pagesize) {
        this.pagesize = pagesize;
    }

    public int getPageno() {
        return pageno;
    }

    public void setPageno(int pageno) {
        this.pageno = pageno;
    }

    public String indexSearchGroup() throws IOException, ElasticsearchException, ArgException {
        String jsonString = "";

        SearchInput si = new SearchInput();
        // si.setIndexName(indexname);
        // si.setTypeNames(typename);

        AggInput ai = new AggInput();
        List<AggBucket> abs = new ArrayList();
        ai.setAggBuckets(abs);
        ai.setIndexName(indexName);
        ai.setTypeNames(typeName);

        ai.setSi(si);

        SearchField sf1 = new SearchField();
        sf1.setField("content");
        sf1.setOperator(SearchConst.SEARCH_OPERATOR_SHOULD);
        sf1.setSearchValue(keywords[0]);

        SearchField sf2 = new SearchField();
        sf2.setField("title");
        sf2.setOperator(SearchConst.SEARCH_OPERATOR_SHOULD);
        sf2.setSearchValue(keywords[0]);

        SearchField[] children = new SearchField[2];
        children[0] = sf1;
        children[1] = sf2;

        SearchField sf12 = new SearchField();
        sf12.setChildrenField(children);
        sf12.setOperator(SearchConst.SEARCH_OPERATOR_MUST);

        ArrayList<SearchField> where = new ArrayList<SearchField>();
        where.add(sf12);

        si.setSearchFields(where);
        si.setReturnFields(new String[] { "hkey", "title", "urlname", "sitename", "pagetime", "content" });


        OrderField sort = new OrderField();
        sort.setFieldName("pagetime");
        sort.setOrder(SearchConst.SEARCH_ORDER_TYPE_DESC);
        si.setOrderFields(new OrderField[] { sort });

        si.setSystemID(SearchConst.PUBLIC_PRIV);
        si.setFrom((pageno - 1) * pagesize);
        si.setSize(pagesize);

        AggBucket ab = new AggBucket();

        ab.setAggName("srcname");
        ab.setField("srcname");
        ab.setSize(10);
        ab.setType(SearchConst.AGG_TYPE_TERMS);

        List<AggBucket> ags = new ArrayList<AggBucket>();
        AggBucket abb = new AggBucket();
        abb.setAggName("month");
        abb.setField("month");
        abb.setSize(10);
        abb.setType(SearchConst.AGG_TYPE_TERMS);
        ags.add(abb);
        ab.setAggBuckets(ags);

        abs.add(ab);
        SearchAndAggResult saar = Searcher.makeAggregation(ai);
        getAggResult(saar.getAggResult(), "");


        // jsonString = rss2Json_group(saar.getAggResult());

        return jsonString;
    }

    private static void getMetricsResult(List<MetricsResult> l) {

        for (MetricsResult mr : l) {
            System.out.println("" + mr.getAggName());
            List<Map<String, Number>> metricsList = mr.getMetrics();
            for (Map<String, Number> map : metricsList) {
                if (map != null) {
                    for (String metricsKey : map.keySet()) {
                        System.out.print(metricsKey + ":");
                        System.out.println(map.get(metricsKey));
                    }
                }
            }
        }
    }

    private static void getAggResult(AggResult ar, String print) {

        List<MetricsResult> l = ar.getMetricsResults();
        if (null != l) {
            getMetricsResult(l);
        }

        Map<String, List<BucketResult>> bMap = ar.getBucketResultMap();
        if (null != bMap) {
            for (String aggName : bMap.keySet()) {
                List<BucketResult> bucketResults = bMap.get(aggName);
                System.out.println(print + aggName);
                for (BucketResult br : bucketResults) {
                    Map<String, AggResult> aggResultMap = br.getBucketAgg();
                    System.out.println(print + "docNumber:" + br.getDocNumber());
                    if (null != aggResultMap) {
                        for (String bucketKey : aggResultMap.keySet()) {
                            System.out.println(print + "   " + bucketKey);
                            getAggResult(aggResultMap.get(bucketKey), print +"\t");

                        }
                    }

                }
            }
        }
    }

    public String rss2JsonGroup(AggResult ar) throws IOException {
        XContentBuilder jsonBuilder = XContentFactory.jsonBuilder();

        jsonBuilder.startObject("facet");

        Map<String, List<BucketResult>> bMap = ar.getBucketResultMap();
        if (null != bMap) {
            for (String aggName : bMap.keySet()) {
                List<BucketResult> bucketResults = bMap.get(aggName);
                jsonBuilder.startArray(aggName);

                for (BucketResult br : bucketResults) {
                    Map<String, AggResult> aggResultMap = br.getBucketAgg();

                    if (null == aggResultMap)
                        continue;

                    Iterator<Map.Entry<String, AggResult>> entries = aggResultMap.entrySet().iterator();

                    if (entries.hasNext()) {

                        Map.Entry<String, AggResult> entry = entries.next();

                        jsonBuilder.startObject();
                        jsonBuilder.field("name", entry.getKey());
                        jsonBuilder.field("count", br.getDocNumber());
                        jsonBuilder.field("total", br.getDocNumber());
                        jsonBuilder.endObject();
                    }
                }
                jsonBuilder.endArray();
            }
        }
        jsonBuilder.endObject();

        String jsonString = jsonBuilder.string();

        return jsonString;
    }


    public String getSearch() throws IOException, ElasticsearchException, ArgException {

        XContentBuilder jsonBuilder = XContentFactory.jsonBuilder();

        return indexSearchGroup();
    }

    public String getDetail(String index, String type, String docID)
            throws IOException, ElasticsearchException, ArgException {

        XContentBuilder jsonBuilder = XContentFactory.jsonBuilder();

        SearchInput si = new SearchInput();
        si.setIndexName(index);
        si.setTypeNames(new String[] { type });

        ArrayList<SearchField> where = new ArrayList<SearchField>();

        if (docID.length() > 0) {
            SearchField sf = new SearchField();
            sf.setField("docid");
            sf.setOperator(SearchConst.SEARCH_OPERATOR_MUST);
            sf.setSearchValue(docID);
            where.add(sf);
        }

        si.setSearchFields(where);
        si.setReturnFields(new String[] { "docid", "anjianmingcheng", "anjianleixing", "reason", "anhao",
                "shenpanchengxu", "caipanyaozhi", "appellor", "legalbase", "fayuanmingcheng", "doccontent", "context",
                "caipanriqi" });

        si.setSystemID("public");
        si.setFrom(0);
        si.setSize(1);

        List<SearchInput> sis = new ArrayList<SearchInput>();
        sis.add(si);

        List<SearchResult> rss = Searcher.multiIndexSearch(sis);

        for (SearchResult rs : rss) {
            jsonBuilder.startObject();

            List<Map> data = rs.getData();
            String key = null;
            Object value = null;
            for (Map<String, String> fields : data) {
                jsonBuilder.startObject("doc");
                Iterator<String> it = fields.keySet().iterator();
                while (it.hasNext()) {
                    key = it.next();
                    value = fields.get(key);

                    if ("_id".equalsIgnoreCase(key) || "_score".equalsIgnoreCase(key))
                        continue;

                    jsonBuilder.field(key, value);
                }
                jsonBuilder.endObject();

                break;
            }

            break;
        }

        jsonBuilder.endObject();

        String jsonString = jsonBuilder.string();

        return jsonString;
    }

    public static void main(String[] args) throws IOException, ElasticsearchException, ArgException {

        // String[] ret = getSuggest("news", "新", 10, false);
        // System.out.println(Arrays.asList(ret));
        //

        Group s = new Group();

        s.setIndexName("artistnews");
        s.setTypeName(new String[] {});
        s.setKeywords(new String[] { "新闻", "规定" });

        s.setPagesize(5);
        s.setPageno(1);

        String ret = s.getSearch();

        System.out.println("++++++++++++++++++json++++++++++++++++++++");
        System.out.println(ret);
        /*
         * String detail = s.getDetail("artistnews", "news",
         * "eb05fd04-224e-4d01-a595-f473f146219c");
         * System.out.println("++++++++++++++++++detail++++++++++++++++++++");
         * System.out.println(detail);
         */

        // s.agg();

        // Searcher.terms("artistnews", "news");
        // Searcher.b();
    }
}
